package com.haoze.nurseapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.enumeration.ConstantEnum;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.DateUtil;
import com.haoze.common.utils.HttpClientUtil;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurseapp.aop.NurseLogAop;
import com.haoze.nurseapp.dao.*;
import com.haoze.nurseapp.dto.*;
import com.haoze.nurseapp.model.PatientTemperatureConfigEntity;
import com.haoze.nurseapp.model.PatientTemperatureEntity;
import com.haoze.nurseapp.model.PatientTemperatureOtherEntity;
import com.haoze.nurseapp.model.PatientTemperatureScheduleEntity;
import com.haoze.nurseapp.service.PatientTemperatureService;
import com.haoze.nurseapp.service.feign.NurseService;
import com.haoze.nurseapp.vo.NurseFileData;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service
public class PatientTemperatureServiceImpl implements PatientTemperatureService {

    @Resource
    PatientTemperatureMapper patientTemperatureMapper;

    @Resource
    PatientTemperatureConfigMapper patientTemperatureConfigMapper;

    @Resource
    PatientInHospitalMapper patientInHospitalMapper;

    @Resource
    PatientTemperatureOtherMapper patientTemperatureOtherMapper;

    @Resource
    PatientTemperatureScheduleMapper patientTemperatureScheduleMapper;
    @Autowired
    private TransfusionServiceImpl transfusionService;

    @Autowired
    NurseService nurseService;

    @Value("${his.url.circulation}")
    private String circulationUrl;

    private static final Logger log = LoggerFactory.getLogger(NurseLogAop.class);

    @Override
    public Result temperatureSave(PatientTemperatureDTO patientTemperatureDTO) {
        List<PatientTemperatureDTO> list = patientTemperatureDTO.getTemperatureList();
        if (list == null || list.size() == 0) {
            return ResultGenerator.genFailedResult("请选择勾选同步内容");
        }
        boolean syncFlage = list.stream().anyMatch(dto -> "1".equals(dto.getSynchronizationFlag()));
        String userName = transfusionService.getCurrentUser().get("userName");
        Date date = DateUtil.stringToDate(patientTemperatureDTO.getSynchronizeTime(), "yyyy-MM-dd HH:mm");
        List<PatientTemperatureDTO> shitList = new ArrayList<>();
        List<PatientTemperatureEntity> insertData = new ArrayList<>();
        AtomicReference<String> twlxCode = new AtomicReference<>("");//01 大编码 体温
        AtomicReference<String> twlxText = new AtomicReference<>("");//01 大编码 体温
        AtomicReference<String> tw = new AtomicReference<>("");//体温值
        AtomicReference<String> mb = new AtomicReference<>("");//脉搏值
        AtomicReference<String> hx = new AtomicReference<>("");//呼吸值
        AtomicReference<String> fhfc = new AtomicReference<>("");//复核复测
        AtomicReference<String> fhtwlxCode = new AtomicReference<>("");//复核 大编码 体温
        AtomicReference<String> fhtwlxText = new AtomicReference<>("");//复核 大编码 体温
        AtomicReference<String> fctwlxCode = new AtomicReference<>("");//复测 大编码 体温
        AtomicReference<String> fctwlxText = new AtomicReference<>("");//复测 大编码 体温
        AtomicReference<String> wlfc = new AtomicReference<>("");//物理复测
        AtomicReference<String> szy = new AtomicReference<>("");//舒张压
        AtomicReference<String> ssy = new AtomicReference<>("");//收缩压
        String inpatNum = list.get(0).getInpatNum() + "-1";
        Pattern pattern = Pattern.compile("^\\d+(\\.\\d{1})?$");
        //体温类型
        list.stream().filter(dto -> StringUtils.isNotBlank(dto.getTemperatureDegreeString()) && pattern.matcher(dto.getTemperatureDegreeString()).matches() && "01".equals(dto.getTemperatureType()) && "1".equals(dto.getSynchronizationFlag())).forEach(dto -> {
            if ("01".equals(dto.getTemperatureSubType())) {//口温
                twlxCode.set("85588d538cff40e097f2274aefc49676");
                tw.set(dto.getTemperatureDegreeString());
                twlxText.set("口温");
            }
            if ("02".equals(dto.getTemperatureSubType())) {//耳温
                twlxCode.set("fd4445af0b22496fae071c09363dad95");
                tw.set(dto.getTemperatureDegreeString());
                twlxText.set("耳温");
            }
            if ("03".equals(dto.getTemperatureSubType())) {//腋温
                twlxCode.set("36a8729c366b40bd9386f54c779d35ab");
                tw.set(dto.getTemperatureDegreeString());
                twlxText.set("腋温");
            }
            if ("04".equals(dto.getTemperatureSubType())) {//肛温
                twlxCode.set("00dff58ea36a43e5b15c1f383e3a5719");
                tw.set(dto.getTemperatureDegreeString());
                twlxText.set("肛温");
            }
            if ("07".equals(dto.getTemperatureSubType())) {//不升
                twlxCode.set("8480daa78a464eb381ec4c9921ff1c03");
                tw.set(dto.getTemperatureDegreeString());
                twlxText.set("不升");
            }
        });
        //脉搏
        list.stream().filter(dto -> StringUtils.isNotBlank(dto.getTemperatureDegreeString()) && pattern.matcher(dto.getTemperatureDegreeString()).matches() && "02".equals(dto.getTemperatureType()) && "1".equals(dto.getSynchronizationFlag())).forEach(dto -> {
            mb.set(dto.getTemperatureDegreeString());
        });
        //呼吸
        list.stream().filter(dto -> StringUtils.isNotBlank(dto.getTemperatureDegreeString()) && pattern.matcher(dto.getTemperatureDegreeString()).matches() && "03".equals(dto.getTemperatureType()) && "1".equals(dto.getSynchronizationFlag())).forEach(dto -> {
            hx.set(dto.getTemperatureDegreeString());
        });
        //复核复测
        list.stream().filter(dto -> StringUtils.isNotBlank(dto.getTemperatureDegreeString()) && pattern.matcher(dto.getTemperatureDegreeString()).matches() && "14".equals(dto.getTemperatureType()) && "1".equals(dto.getSynchronizationFlag())).forEach(dto -> {
            fhfc.set(dto.getTemperatureDegreeString());
        });
        //复核复测-体温类型
        list.stream().filter(dto -> StringUtils.isNotBlank(dto.getTemperatureDegreeString()) && pattern.matcher(dto.getTemperatureDegreeString()).matches() && "14".equals(dto.getTemperatureType()) && "1".equals(dto.getSynchronizationFlag())).forEach(dto -> {
            if ("01".equals(dto.getTemperatureSubType())) {//口温
                fhtwlxCode.set("85588d538cff40e097f2274aefc49676");
                fhtwlxText.set("口温");
            }
            if ("02".equals(dto.getTemperatureSubType())) {//耳温
                fhtwlxCode.set("fd4445af0b22496fae071c09363dad95");
                fhtwlxText.set("耳温");
            }
            if ("03".equals(dto.getTemperatureSubType())) {//腋温
                fhtwlxCode.set("36a8729c366b40bd9386f54c779d35ab");
                fhtwlxText.set("腋温");
            }
            if ("04".equals(dto.getTemperatureSubType())) {//肛温
                fhtwlxCode.set("00dff58ea36a43e5b15c1f383e3a5719");
                fhtwlxText.set("肛温");
            }
        });
        //物理复测
        list.stream().filter(dto -> StringUtils.isNotBlank(dto.getTemperatureDegreeString()) && pattern.matcher(dto.getTemperatureDegreeString()).matches() && "13".equals(dto.getTemperatureType()) && "1".equals(dto.getSynchronizationFlag())).forEach(dto -> {
            wlfc.set(dto.getTemperatureDegreeString());
        });
        //物理复测-体温类型
        list.stream().filter(dto -> StringUtils.isNotBlank(dto.getTemperatureDegreeString()) && pattern.matcher(dto.getTemperatureDegreeString()).matches() && "13".equals(dto.getTemperatureType()) && "1".equals(dto.getSynchronizationFlag())).forEach(dto -> {
            if ("01".equals(dto.getTemperatureSubType())) {//口温
                fctwlxCode.set("85588d538cff40e097f2274aefc49676");
                fctwlxText.set("口温");
            }
            if ("02".equals(dto.getTemperatureSubType())) {//耳温
                fctwlxCode.set("fd4445af0b22496fae071c09363dad95");
                fctwlxText.set("耳温");
            }
            if ("03".equals(dto.getTemperatureSubType())) {//腋温
                fctwlxCode.set("36a8729c366b40bd9386f54c779d35ab");
                fctwlxText.set("腋温");
            }
            if ("04".equals(dto.getTemperatureSubType())) {//肛温
                fctwlxCode.set("00dff58ea36a43e5b15c1f383e3a5719");
                fctwlxText.set("肛温");
            }
        });
        //舒张压
        list.stream().filter(dto -> StringUtils.isNotBlank(dto.getTemperatureDegreeString()) && pattern.matcher(dto.getTemperatureDegreeString()).matches() && "05".equals(dto.getTemperatureType()) && ("03".equals(dto.getTemperatureSubType()) || "04".equals(dto.getTemperatureSubType())) && "1".equals(dto.getSynchronizationFlag())).forEach(dto -> {
            szy.set(dto.getTemperatureDegreeString());
        });
        //收缩压
        list.stream().filter(dto -> StringUtils.isNotBlank(dto.getTemperatureDegreeString()) && pattern.matcher(dto.getTemperatureDegreeString()).matches() && "05".equals(dto.getTemperatureType()) && ("01".equals(dto.getTemperatureSubType()) || "02".equals(dto.getTemperatureSubType())) && "1".equals(dto.getSynchronizationFlag())).forEach(dto -> {
            ssy.set(dto.getTemperatureDegreeString());
        });
        patientTemperatureMapper.deleteGuoMingYaoWu(inpatNum, list.get(0).getMeasurementDate().substring(0, 10));
        for (PatientTemperatureDTO dto : list) {


            if (("15".equals(dto.getTemperatureType()) && "01".equals(dto.getTemperatureSubType())) || ("08".equals(dto.getTemperatureType()) && "01".equals(dto.getTemperatureSubType()))) {
                //判断特殊处理类型数据
                if ("08".equals(dto.getTemperatureType()) && "01".equals(dto.getTemperatureSubType())) { //08type 01subtype 大便
                    shitList.add(dto);
                }
                PatientTemperatureOtherEntity patientTemperatureOtherEntity = new PatientTemperatureOtherEntity();
                BeanUtils.copyProperties(dto, patientTemperatureOtherEntity);
                patientTemperatureOtherEntity.setPatientTemperatureOtherId(UUIDUtil.randomString());
                patientTemperatureOtherEntity.setCreateTime(new Date());
                patientTemperatureOtherEntity.setModifyTime(new Date());
                patientTemperatureOtherEntity.setDataVersion(1);
                patientTemperatureOtherEntity.setHospitalId("80D024E29BF40C9DE0537A5B14AC1620");
                patientTemperatureOtherEntity.setMenuName(dto.getFieldName());
                patientTemperatureOtherEntity.setMeasurementDate(DateUtil.stringToDate(dto.getMeasurementDate(), "yyyy-MM-dd"));
                patientTemperatureOtherEntity.setDataValue(dto.getTemperatureDegreeString());
                patientTemperatureOtherEntity.setInpatNum(inpatNum);
                patientTemperatureOtherEntity.setMenuUtil(dto.getTemperatureUnit());
//                if (StringUtils.isNotEmpty(patientTemperatureOtherEntity.getDataValue())) {
                patientTemperatureOtherMapper.saveOrUpdate(patientTemperatureOtherEntity);
//                }
            } else {
//                boolean addFlag = false;
//                if (("01".equals(dto.getTemperatureType()) && ("05".equals(dto.getTemperatureSubType()) || "06".equals(dto.getTemperatureSubType()))) ||
//                        ("02".equals(dto.getTemperatureType()) && ("02".equals(dto.getTemperatureSubType()) || "03".equals(dto.getTemperatureSubType()))) ||
//                        (("03".equals(dto.getTemperatureType()) || "04".equals(dto.getTemperatureType())) && ("03".equals(dto.getTemperatureSubType()) || "04".equals(dto.getTemperatureSubType()))) ||
//                        (("13".equals(dto.getTemperatureType()) || "14".equals(dto.getTemperatureType())) && ("05".equals(dto.getTemperatureSubType()) || "06".equals(dto.getTemperatureSubType())))) {
//                    addFlag = true;
//                }
                //过敏药物修改频率
                if ("12".equals(dto.getTemperatureType()) && StringUtils.isNotEmpty(dto.getDeptId()) && StringUtils.isNotEmpty(dto.getDataCode())) {
                    patientTemperatureMapper.saveOrUpdateStat(dto.getDeptId(), dto.getDataCode());
                }
                PatientTemperatureEntity patientTemperatureEntity = new PatientTemperatureEntity();
                BeanUtils.copyProperties(dto, patientTemperatureEntity);
                patientTemperatureEntity.setTemperatureId(UUIDUtil.randomString());
                patientTemperatureEntity.setCreateTime(new Date());
                patientTemperatureEntity.setModifyTime(new Date());
                patientTemperatureEntity.setMeasurementDate(DateUtil.stringToDate(dto.getMeasurementDate(), "yyyy-MM-dd HH:mm"));
                patientTemperatureEntity.setDataVersion(1);
                patientTemperatureEntity.setHospitalId("80D024E29BF40C9DE0537A5B14AC1620");
                patientTemperatureEntity.setInpatNum(inpatNum);
//                if (StringUtils.isNotEmpty(patientTemperatureEntity.getTemperatureDegreeString()) || addFlag) {
                if (patientTemperatureEntity.getTemperatureDegreeString() != null && pattern.matcher(patientTemperatureEntity.getTemperatureDegreeString()).matches()) {
                    patientTemperatureEntity.setTemperatureDegree(patientTemperatureEntity.getTemperatureDegreeString());
                }
                insertData.add(patientTemperatureEntity);
//                }
            }
        }
        String shitRes = "";
        String shit = "";
        String shitTimes = "";
        String enemaShitTimes = "";
        String enemaAfterShitTimes = "";
        Date shitEntityDate = null;
        for (PatientTemperatureDTO shitDto : shitList) {
            if ("shit".equals(shitDto.getFieldName())) {
                shit = shitDto.getTemperatureDegreeString();
                shitEntityDate = DateUtil.stringToDate(shitDto.getMeasurementDate(), "yyyy-MM-dd");
            } else if ("shitTimes".equals(shitDto.getFieldName())) {
                shitTimes = shitDto.getTemperatureDegreeString();
            } else if ("enemaShitTimes".equals(shitDto.getFieldName())) {//灌肠次数
                enemaShitTimes = shitDto.getTemperatureDegreeString();
            } else if ("enemaAfterShitTimes".equals(shitDto.getFieldName())) {//灌肠后大便次数
                enemaAfterShitTimes = shitDto.getTemperatureDegreeString();
            }
        }
        if ("※".equals(shit) || "☆".equals(shit)) {
            shitRes = shit;
        } else if (StringUtils.isNotBlank(enemaShitTimes) && StringUtils.isNotBlank(enemaAfterShitTimes)) {
            if ("1".equals(enemaShitTimes)) {
                enemaShitTimes = "";
            }
            if ("0".equals(shitTimes) || "".equals(shitTimes)) {
                shitRes = "(" + enemaAfterShitTimes + "/" + enemaShitTimes + "E)";
            } else {
                shitRes = shitTimes + "(" + enemaAfterShitTimes + "/" + enemaShitTimes + "E)";
            }
        } else {
            shitRes = shitTimes;
        }
        PatientTemperatureEntity shitEntity = new PatientTemperatureEntity();
        BeanUtils.copyProperties(shitList.get(0), shitEntity);
        shitEntity.setTemperatureDegreeString(shitRes);
        shitEntity.setTemperatureId(UUIDUtil.randomString());
        shitEntity.setCreateTime(new Date());
        shitEntity.setModifyTime(new Date());
        shitEntity.setMeasurementDate(shitEntityDate);
        shitEntity.setDataVersion(1);
        shitEntity.setHospitalId("80D024E29BF40C9DE0537A5B14AC1620");
        shitEntity.setInpatNum(inpatNum);
        insertData.add(shitEntity);

        insertData.stream().forEach(x -> {
            if ("12".equals(x.getTemperatureType())) {
                patientTemperatureMapper.insert(x);
            } else {
                patientTemperatureMapper.saveOrUpdate(x);
            }
        });
        //同步护理记录单
        if (syncFlage) {
            String bedNo = patientTemperatureMapper.selecPatient(inpatNum).get("bedNo");
            if (StringUtils.isNotBlank(fhfc.get())) {
                tw.set(fhfc.get());
            }
            if (date.getTime() > new Date().getTime()) {
                JSONObject jsonData = new JSONObject();
                PatientTemperatureScheduleEntity scheduleEntity = new PatientTemperatureScheduleDTO();
                scheduleEntity.setTemperatureScheduleId(UUIDUtil.randomString());
                scheduleEntity.setCreateTime(new Date());
                scheduleEntity.setModifyTime(new Date());
                scheduleEntity.setDataVersion(1);
                scheduleEntity.setHospitalId("80D024E29BF40C9DE0537A5B14AC1620");
                scheduleEntity.setExecutionTime(date);
                jsonData.put("twlxCode", StringUtils.isBlank(fhtwlxCode.get()) ? twlxCode.get() : fhtwlxCode.get());
                jsonData.put("twlxText", StringUtils.isBlank(fhtwlxText.get()) ? twlxText.get() : fhtwlxText.get());
                jsonData.put("tw", tw.get());
                jsonData.put("mb", mb.get());
                jsonData.put("hx", hx.get());
                jsonData.put("szy", szy.get());
                jsonData.put("ssy", ssy.get());
                jsonData.put("inpatNum", inpatNum);
                jsonData.put("bedNo", bedNo);
                jsonData.put("date", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm"));
                jsonData.put("userName", userName);
                scheduleEntity.setStatus("0");
                scheduleEntity.setDataJson(jsonData.toJSONString());
                patientTemperatureScheduleMapper.insert(scheduleEntity);
            } else {
                nurseFileSave(StringUtils.isBlank(fhtwlxCode.get()) ? twlxCode.get() : fhtwlxCode.get(), StringUtils.isBlank(fhtwlxText.get()) ? twlxText.get() : fhtwlxText.get(), tw.get(), mb.get(), hx.get(), szy.get(), ssy.get(), inpatNum, bedNo, date, userName);
            }
            if (StringUtils.isNotBlank(wlfc.get())) {
                Date fhDate = new Date(date.getTime() + (1000 * 60 * 30));
                if (date.getTime() > new Date().getTime()) {
                    JSONObject jsonData = new JSONObject();
                    PatientTemperatureScheduleEntity scheduleEntity = new PatientTemperatureScheduleDTO();
                    scheduleEntity.setTemperatureScheduleId(UUIDUtil.randomString());
                    scheduleEntity.setCreateTime(new Date());
                    scheduleEntity.setModifyTime(new Date());
                    scheduleEntity.setDataVersion(1);
                    scheduleEntity.setHospitalId("80D024E29BF40C9DE0537A5B14AC1620");
                    scheduleEntity.setExecutionTime(fhDate);
                    jsonData.put("twlxCode", fctwlxCode.get());
                    jsonData.put("twlxText", fctwlxText.get());
                    jsonData.put("tw", wlfc.get());
                    jsonData.put("userName", userName);
//                jsonData.put("mb", mb);
//                jsonData.put("hx", hx);
//                jsonData.put("szy", szy);
//                jsonData.put("ssy", ssy);
                    jsonData.put("inpatNum", inpatNum);
                    jsonData.put("bedNo", bedNo);
                    jsonData.put("date", DateUtil.dateToString(fhDate, "yyyy-MM-dd HH:mm"));
                    scheduleEntity.setStatus("0");
                    scheduleEntity.setDataJson(jsonData.toJSONString());
                    patientTemperatureScheduleMapper.insert(scheduleEntity);
                } else {
                    nurseFileSave(fctwlxCode.get(), fctwlxText.get(), wlfc.get(), "", "", "", "", inpatNum, bedNo, fhDate, userName);//复测30分钟后的数据
                }
            }
        }
        return ResultGenerator.genOkResult();
    }


    public void nurseFileSave(String twlxCode, String twlxText, String tw, String mb, String hx, String szy, String ssy, String inpatNum, String bedNo, Date date, String userName) {
        String fileId = patientTemperatureMapper.selecRecordId(inpatNum, DateUtil.dateToString(date, "yyyy-MM-dd HH:mm"));
        if (StringUtils.isNotBlank(fileId)) {
            Result result = nurseService.oneRecord(fileId, inpatNum, "0");
            Map ds = (Map) result.getData();
            List<NurseFileData> fileList = JSON.parseArray(JSON.toJSONString(ds.get("emrFileDataList")), NurseFileData.class);
            fileList.stream().forEach(t -> {
                //不升,特殊情况处理,不同数据元
                if ("8480daa78a464eb381ec4c9921ff1c03".equals(twlxCode)) {
                    if ("10d4c519f5e24cf98dbe0b2f50b4d160".equals(t.getElement().getId())) {//体温状态
                        if (StringUtils.isNotBlank(twlxText)) {
                            t.getFileIndexDataEntity().setDataCode(twlxCode);
                            t.getFileIndexDataEntity().setDataValue(twlxText);
                        }
                    }
                } else {
                    if ("7f3f9dbead1b4540aa9922e442d0b63a".equals(t.getElement().getId())) {//体温类型
                        if (StringUtils.isNotBlank(twlxText)) {
                            t.getFileIndexDataEntity().setDataCode(twlxCode);
                            t.getFileIndexDataEntity().setDataValue(twlxText);
                        }
                    }
                }
                if ("7F8AF946243C7555E0537A5B14ACC42E".equals(t.getElement().getId())) {//体温温度
                    if (StringUtils.isNotBlank(tw)) {
                        t.getFileIndexDataEntity().setDataValue(tw);
                    }
                }
                if ("b17ec5ef63744137b7eab90f8b45926e".equals(t.getElement().getId())) {//脉搏 值
                    if (StringUtils.isNotBlank(mb)) {
                        t.getFileIndexDataEntity().setDataValue(mb);
                    }
                }
                if ("7F8AF94622797555E0537A5B14ACC42E".equals(t.getElement().getId())) {//呼吸
                    if (StringUtils.isNotBlank(hx)) {
                        t.getFileIndexDataEntity().setDataValue(hx);
                    }
                }
                if ("7F8AF946243A7555E0537A5B14ACC42E".equals(t.getElement().getId())) {//收缩压(mmHg)
                    if (StringUtils.isNotBlank(ssy)) {
                        t.getFileIndexDataEntity().setDataValue(ssy);
                    }
                }
                if ("7F8AF946243B7555E0537A5B14ACC42E".equals(t.getElement().getId())) {//舒张压(mmHg)
                    if (StringUtils.isNotBlank(szy)) {
                        t.getFileIndexDataEntity().setDataValue(szy);
                    }
                }
            });

            JSONObject parm = new JSONObject();
            parm.put("emrFileDataList", fileList);
            parm.put("recordType", "0");
            parm.put("inpatNum", inpatNum);
            parm.put("bedNo", bedNo);
            parm.put("recordTime", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm"));
            parm.put("fileDataId", fileId);
            String json = parm.toJSONString();
            Result sd = nurseService.editSave(json);
            log.info("护理文书记录单修改返回:{}", sd);

        } else {
            Result result = nurseService.create(inpatNum, "0");
            Map ds = (Map) result.getData();
            List<NurseFileData> fileList = JSON.parseArray(JSON.toJSONString(ds.get("emrFileDataList")), NurseFileData.class);
            List<NurseFileData> finalFileList = new ArrayList<>();
            fileList.parallelStream().forEach(nurse -> {
                if ("ck_jlsmtz".equals(nurse.getElement().getVarCode())) {
                    finalFileList.addAll(nurse.getEmrFileDataList());
                } else {
                    finalFileList.add(nurse);
                }
            });
            finalFileList.parallelStream().filter(file -> "ck_jlhsqm".equals(file.getElement().getVarCode())).forEach(file -> file.getFileIndexDataEntity().setDataValue(userName));
            finalFileList.stream().forEach(t -> {
                //不升,特殊情况处理,不同数据元
                if ("8480daa78a464eb381ec4c9921ff1c03".equals(twlxCode)) {
                    if ("10d4c519f5e24cf98dbe0b2f50b4d160".equals(t.getElement().getId())) {//体温状态
                        if (StringUtils.isNotBlank(twlxText)) {
                            t.getFileIndexDataEntity().setDataCode(twlxCode);
                            t.getFileIndexDataEntity().setDataValue(twlxText);
                        }
                    }
                } else {
                    if ("7f3f9dbead1b4540aa9922e442d0b63a".equals(t.getElement().getId())) {//体温类型
                        if (StringUtils.isNotBlank(twlxText)) {
                            t.getFileIndexDataEntity().setDataCode(twlxCode);
                            t.getFileIndexDataEntity().setDataValue(twlxText);
                        }
                    }
                }
                if ("7F8AF946243C7555E0537A5B14ACC42E".equals(t.getElement().getId())) {//体温温度
                    if (StringUtils.isNotBlank(tw)) {
                        t.getFileIndexDataEntity().setDataValue(tw);
                    }
                }
                if ("b17ec5ef63744137b7eab90f8b45926e".equals(t.getElement().getId())) {//脉搏 值
                    if (StringUtils.isNotBlank(mb)) {
                        t.getFileIndexDataEntity().setDataValue(mb);
                    }
                }
                if ("7F8AF94622797555E0537A5B14ACC42E".equals(t.getElement().getId())) {//呼吸
                    if (StringUtils.isNotBlank(hx)) {
                        t.getFileIndexDataEntity().setDataValue(hx);
                    }
                }
                if ("7F8AF946243A7555E0537A5B14ACC42E".equals(t.getElement().getId())) {//收缩压(mmHg)
                    if (StringUtils.isNotBlank(ssy)) {
                        t.getFileIndexDataEntity().setDataValue(ssy);
                    }
                }
                if ("7F8AF946243B7555E0537A5B14ACC42E".equals(t.getElement().getId())) {//舒张压(mmHg)
                    if (StringUtils.isNotBlank(szy)) {
                        t.getFileIndexDataEntity().setDataValue(szy);
                    }
                }
            });

            JSONObject parm = new JSONObject();
            parm.put("emrFileDataList", finalFileList);
            parm.put("recordType", "0");
            parm.put("inpatNum", inpatNum);
            parm.put("bedNo", bedNo);
            parm.put("recordTime", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm"));
            parm.put("fileDataId", "");
            String json = parm.toJSONString();
            Result sd = nurseService.save(json);
            log.info("护理文书记录单插入返回:{}", sd);
        }
    }

    @Override
    public Result queryTemperatureConfig(PatientTemperatureConfigDTO patientTemperatureConfigDTO) {
        List<PatientTemperatureConfigDTO> result = patientTemperatureMapper.selectConfig(patientTemperatureConfigDTO.getWardDeptId(), patientTemperatureConfigDTO.getFlag());

        if (result == null || result.size() == 0) {
            String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
            List<Map<String, String>> configDictList = patientTemperatureMapper.selectConfigDict();
            List<PatientTemperatureConfigDTO> insertData = new ArrayList();
            for (Map<String, String> config : configDictList) {
                PatientTemperatureConfigEntity entity = new PatientTemperatureConfigEntity();
                entity.setPatientTemperatureConfigId(UUIDUtil.randomString());
                entity.setCreateTime(new Date());
                entity.setModifyTime(new Date());
                entity.setDataVersion(1);
                entity.setHospitalId("80D024E29BF40C9DE0537A5B14AC1620");
                entity.setCreateUserId(userId);
                entity.setWardDeptId(patientTemperatureConfigDTO.getWardDeptId());
                String dataValue = config.get("DATA_VALUE");
                String dataValueRemark = config.get("DATA_VALUE_REMARK");//fileName
                String menuName = dataValue.split("-")[0];
                String menuUtil = "";
                if (dataValue.split("-").length > 1) {
                    menuUtil = dataValue.split("-")[1];
                }
                entity.setMenuName(menuName);
                entity.setMenuUtil(menuUtil);
                entity.setFieldName(dataValueRemark);
                entity.setOpertionDatetime(new Date());
                entity.setDelFlag("0");
                entity.setModifyUserId(userId);
                patientTemperatureConfigMapper.insert(entity);
                PatientTemperatureConfigDTO dto = new PatientTemperatureConfigDTO();
                BeanUtils.copyProperties(entity, dto);
                insertData.add(dto);
            }
            return ResultGenerator.genOkResult(insertData);
        } else {
            return ResultGenerator.genOkResult(result);
        }
    }

    @Override
    public Result updateTemperatureConfig(List<PatientTemperatureConfigDTO> list) {
        for (PatientTemperatureConfigDTO dto : list) {
            PatientTemperatureConfigEntity entity = new PatientTemperatureConfigEntity();
            BeanUtils.copyProperties(dto, entity);
            patientTemperatureConfigMapper.updateByPrimaryKey(entity);
        }
        return ResultGenerator.genOkResult();
    }

    @Override
    public Result saveTemperature(PatientTemperatureConfigDTO patientTemperatureConfigDTO) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        patientTemperatureConfigDTO.setPatientTemperatureConfigId(UUIDUtil.randomString());
        patientTemperatureConfigDTO.setCreateTime(new Date());
        patientTemperatureConfigDTO.setModifyTime(new Date());
        patientTemperatureConfigDTO.setDataVersion(1);
        patientTemperatureConfigDTO.setHospitalId("80D024E29BF40C9DE0537A5B14AC1620");
        patientTemperatureConfigDTO.setCreateUserId(userId);
        patientTemperatureConfigDTO.setWardDeptId(patientTemperatureConfigDTO.getWardDeptId());
        patientTemperatureConfigDTO.setOpertionDatetime(new Date());
        patientTemperatureConfigDTO.setDelFlag("0");
        patientTemperatureConfigDTO.setModifyUserId(userId);
        if (StringUtils.isBlank(patientTemperatureConfigDTO.getMenuName()) ||
                StringUtils.isBlank(patientTemperatureConfigDTO.getMenuUtil()) || StringUtils.isBlank(patientTemperatureConfigDTO.getWardDeptId())) {
            return ResultGenerator.genFailedResult("名称,单位,病区ID都不可为空");
        }
        patientTemperatureConfigMapper.insert(patientTemperatureConfigDTO);
        return ResultGenerator.genOkResult();
    }

    @Override
    public Result deleteTemperature(List<PatientTemperatureConfigDTO> patientTemperatureConfigDTO) {
        for (PatientTemperatureConfigDTO dto : patientTemperatureConfigDTO) {
            patientTemperatureConfigMapper.delete(dto);
        }
        return ResultGenerator.genOkResult();
    }

    @Override
    public Result getDrugList(Integer page, Integer pageSize, String search) {
        PageHelper.startPage(page, pageSize);
        List<OrderTypeDTO> list = patientTemperatureMapper.getDrugDicts(search);
        return ResultGenerator.genOkResult(new PageInfo(list));
    }

    @Override
    public Result getNearTime() {
        //2:00,6:00,10:00,14:00,18:00,22:00 获取离时间点最近的一个
        String dateStr = DateUtil.dateToString(new Date(), "yyyy-MM-dd");
        long dateLong = new Date().getTime();
        List<Map> list = new ArrayList<>();
        String[] times = {" 02:00:00", " 06:00:00", " 10:00:00", " 14:00:00", " 18:00:00", " 22:00:00"};
        for (String time : times) {
            Map timeMap = new HashMap();
            timeMap.put("timeLong", Math.abs(DateUtil.stringToDate(dateStr + time, "yyyy-MM-dd HH:mm:ss").getTime() - dateLong));
            timeMap.put("timeLong2", DateUtil.stringToDate(dateStr + time, "yyyy-MM-dd HH:mm:ss").getTime() - dateLong);
            list.add(timeMap);
        }
        list = list.stream().sorted(Comparator.comparing(PatientTemperatureServiceImpl::comparingByTime)).collect(Collectors.toList());
        String dateRes = DateUtil.dateToString(new Date(Long.parseLong(list.get(0).get("timeLong2").toString()) + dateLong), "HH:mm");
        return ResultGenerator.genOkResult(dateRes);
    }

    private static Long comparingByTime(Map a) {
        return Long.parseLong(a.get("timeLong").toString());
    }

    @Override
    public Result getNurseFileData(String inpatNum, String date) {
        List<Map<String, String>> fileData = patientTemperatureMapper.selecRecord(inpatNum, date);
        List res = new CopyOnWriteArrayList();
        String temType = "";
        String temSubType = "";
        String temData = "";
        for (Map<String, String> item : fileData) {
            Map<String, String> data = new HashMap<>();
            //体温类型
            //看一下 不升是否不选择也会存入表数据中 应该判断上一个大节点选择的datacode，此处判断有误
            if ("10d4c519f5e24cf98dbe0b2f50b4d160".equals(item.get("ELEMENT_ID")) && "8480daa78a464eb381ec4c9921ff1c03".equals(item.get("DATA_CODE"))) {
                temType = "01";
                temSubType = "07";
                temData = "不升";
            } else {
                //第一个下拉选不是不升  第二个下拉选判断 判断体温的elementId 与 datacode
                if (StringUtils.isBlank(temType)) {
                    if ("7f3f9dbead1b4540aa9922e442d0b63a".equals(item.get("ELEMENT_ID")) && "85588d538cff40e097f2274aefc49676".equals(item.get("DATA_CODE"))) {//口温
                        temType = "01";
                        temSubType = "01";
                    } else if ("7f3f9dbead1b4540aa9922e442d0b63a".equals(item.get("ELEMENT_ID")) && "fd4445af0b22496fae071c09363dad95".equals(item.get("DATA_CODE"))) {//耳温
                        temType = "01";
                        temSubType = "02";
                    } else if ("7f3f9dbead1b4540aa9922e442d0b63a".equals(item.get("ELEMENT_ID")) && "36a8729c366b40bd9386f54c779d35ab".equals(item.get("DATA_CODE"))) {//腋温
                        temType = "01";
                        temSubType = "03";
                    } else if ("7f3f9dbead1b4540aa9922e442d0b63a".equals(item.get("ELEMENT_ID")) && "00dff58ea36a43e5b15c1f383e3a5719".equals(item.get("DATA_CODE"))) {//肛温
                        temType = "01";
                        temSubType = "04";
                    }
                }
            }

//            if("10d4c519f5e24cf98dbe0b2f50b4d160".equals(item.get("ELEMENT_ID"))){//体温不升特殊處理 先判断是不是不升，如不是则是正常体温
//                temType = "01";
//                temSubType = "07";
//                temData = "不升";
//            }else if("7f3f9dbead1b4540aa9922e442d0b63a".equals(item.get("ELEMENT_ID"))){
//                if("85588d538cff40e097f2274aefc49676".equals(item.get("DATA_CODE"))){//口温
//                    temType = "01";
//                    temSubType = "01";
//                }else if("fd4445af0b22496fae071c09363dad95".equals(item.get("DATA_CODE"))){//耳温
//                    temType = "01";
//                    temSubType = "02";
//                }else if("36a8729c366b40bd9386f54c779d35ab".equals(item.get("DATA_CODE"))){//腋温
//                    temType = "01";
//                    temSubType = "03";
//                }else if("00dff58ea36a43e5b15c1f383e3a5719".equals(item.get("DATA_CODE"))){//肛温
//                    temType = "01";
//                    temSubType = "04";
//                }
//            }
            if ("7F8AF946243C7555E0537A5B14ACC42E".equals(item.get("ELEMENT_ID"))) {//体温温度
                if (StringUtils.isBlank(temData)) {
                    temData = item.get("DATA_VALUE");
                }
            }
            if ("b17ec5ef63744137b7eab90f8b45926e".equals(item.get("ELEMENT_ID"))) {//脉搏 值
                data.put("temperatureType", "02");
                data.put("temperatureSubType", "01");
                data.put("temperatureDegreeString", item.get("DATA_VALUE"));
                res.add(data);
            }
            if ("7F8AF94622797555E0537A5B14ACC42E".equals(item.get("ELEMENT_ID"))) {//呼吸
                data.put("temperatureType", "03");
                data.put("temperatureSubType", "01");
                data.put("temperatureDegreeString", item.get("DATA_VALUE"));
                res.add(data);
            }
            if ("7F8AF946243A7555E0537A5B14ACC42E".equals(item.get("ELEMENT_ID"))) {//收缩压(mmHg)
                data.put("temperatureType", "05");
                data.put("temperatureSubType", "07");
                data.put("temperatureDegreeString", item.get("DATA_VALUE"));
                res.add(data);
            }

            if ("b6e2b4b72fcc4d8c99b0e19cf9e37616".equals(item.get("ELEMENT_ID"))) {//入量值
                data.put("temperatureType", "06");
                data.put("temperatureSubType", "01");
                data.put("temperatureDegreeString", item.get("DATA_VALUE"));
                res.add(data);
            }
            if ("e927d3b765344877a16468c9986318e6".equals(item.get("ELEMENT_ID"))) {//出量值
                data.put("temperatureType", "07");
                data.put("temperatureSubType", "01");
                data.put("temperatureDegreeString", item.get("DATA_VALUE"));
                res.add(data);
            }

        }
        if (StringUtils.isNotBlank(temType) && StringUtils.isNotBlank(temSubType) && StringUtils.isNotBlank(temData)) {
            Map data = new HashMap();
            data.put("temperatureType", temType);
            data.put("temperatureSubType", temSubType);
            data.put("temperatureDegreeString", temData);
            res.add(data);
        }
        return ResultGenerator.genOkResult(res);
    }

    @Override
    public Result selectVolume(String inpatNum) {
        List<Map<String, String>> volume = patientTemperatureMapper.selectVolume(inpatNum);
        List<Map<String, String>> volumeRes = new ArrayList<>();
        for (Map<String, String> item : volume) {
            Map<String, String> itemMap = new HashMap<>();
            if (item.get("DATA_TEXT").equals("总入量")) {
                itemMap.put("inData", item.get("DATA_VALUE"));
            } else {
                itemMap.put("outData", item.get("DATA_VALUE"));
            }
            volumeRes.add(itemMap);
        }
        return ResultGenerator.genOkResult(volumeRes);
    }

    @Override
    public Result queryTimeData(String inpatNum, String date) {
        this.computeSummary(inpatNum + "-1", DateUtil.dateToString(DateUtil.stringToDate(date), "yyyy-MM-dd"));
        List<PatientTemperatureDTO> list = patientTemperatureMapper.queryTimeData(inpatNum + "-1", date);
        return ResultGenerator.genOkResult(list);
    }

    @Override
    public Result queryTimeDataForPc(String inpatNum, String day) {
        Map<String, Object> timeModMap = new HashMap<>();
        timeModMap.put("02:00:00", "");
        timeModMap.put("06:00:00", "");
        timeModMap.put("10:00:00", "");
        timeModMap.put("14:00:00", "");
        timeModMap.put("18:00:00", "");
        timeModMap.put("22:00:00", "");
        timeModMap.entrySet().forEach(obj -> {
            List<PatientTemperatureDTO> tempList = patientTemperatureMapper.queryTempTimeData(inpatNum + "-1", day + " " + obj.getKey());
            tempList.stream().forEach(dto -> {
                if (isNumeric(dto.getTemperatureDegree())) {
                    dto.setTemperatureDegreeString(new BigDecimal(String.valueOf(dto.getTemperatureDegree())).stripTrailingZeros().toPlainString());
                }
            });
            obj.setValue(tempList);
        });
        this.computeSummary(inpatNum + "-1", day);
        List<PatientTemperatureDTO> list = patientTemperatureMapper.queryTimeDataByDay(inpatNum + "-1", day);
        list.stream().forEach(dto -> {
            if (isNumeric(dto.getTemperatureDegree())) {
                dto.setTemperatureDegreeString(new BigDecimal(String.valueOf(dto.getTemperatureDegree())).stripTrailingZeros().toPlainString());
            }
        });
        Map<String, Object> result = new HashMap<>();
        result.put("hourData", timeModMap);
        result.put("dayData", list);
        return ResultGenerator.genOkResult(result);
    }

    @Override
    public Result queryTimeForDelivery(String inpatNum) {
        Map<String, Date> times = patientTemperatureMapper.selectDeliveryAndBackRoomTimeByInpatNum(inpatNum);
        final HashMap<String, String> map = new HashMap<>();
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        final String deliveryTime = "deliveryTime";
        final String backRoomTime = "backRoomTime";
        if (times == null) {
            map.put(deliveryTime, "");
            map.put(backRoomTime, "");
        }else {
            map.put(deliveryTime, times.get(deliveryTime) == null ? "" : formatter.format(LocalDateTime.ofInstant(times.get(deliveryTime).toInstant(), ZoneId.systemDefault())));
            map.put(backRoomTime, times.get(backRoomTime) == null ? "" : formatter.format(LocalDateTime.ofInstant(times.get(backRoomTime).toInstant(), ZoneId.systemDefault())));
        }
        return ResultGenerator.genOkResult(map);
    }

    @Override
    public Result saveTimeForDelivery(DeliveryInputDTO deliveryInputDTO) {
        // 同步数据到his
        updateToHis(deliveryInputDTO);
        patientTemperatureMapper.updateDeliveryInputByInpatNum(deliveryInputDTO.getInpatNum(), deliveryInputDTO.getDeliveryTime(), deliveryInputDTO.getBackRoomTime());
        return ResultGenerator.genOkResult();
    }

    /**
     * 同步数据到his
     * @param deliveryInputDTO
     */
    private void updateToHis(DeliveryInputDTO deliveryInputDTO) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        log.info("updateToHis userId:{}", userId);
        String personCode = patientInHospitalMapper.queryPersonCodeByUserId(userId);
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        final String optTime = formatter.format(LocalDateTime.now());
        final String[] split = deliveryInputDTO.getInpatNum().split("-");
        final Map<String, Object> map = new HashMap<>();
        final Map<String, Object> request = new HashMap<>();
        final Map<String, Object> param = new HashMap<>();
        param.put("opr_type", "U");
        param.put("patient_id", split[0]);
        param.put("visit_id", Integer.valueOf(split[1]));
        param.put("operator", personCode);
        param.put("operationdate", optTime);
        param.put("brith", formatter.format(LocalDateTime.ofInstant(deliveryInputDTO.getDeliveryTime().toInstant(), ZoneId.systemDefault())));
        param.put("brith_back_room", formatter.format(LocalDateTime.ofInstant(deliveryInputDTO.getBackRoomTime().toInstant(), ZoneId.systemDefault())));
        request.put("request", param);
        map.put("c_request", request);
        map.put("operationID", ConstantEnum.HIS_DELIVERY_10037.getKey());
        log.info("updateToHis request body:{}", map);
        final JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl, map);
        log.info("updateToHis response body:{}", jsonObject);
        final JSONObject cResponse = (JSONObject) jsonObject.get("c_response");
        final JSONObject response = (JSONObject) cResponse.get("response");
        final Integer errorId = (Integer) response.get("error_id");
        final String errorMsg = (String) response.get("error_msg");
        final JSONArray list = (JSONArray) response.get("list");
        log.info("updateToHis response errorId:{}", errorId);
        if (1 != errorId) {
            // 响应失败
            throw new RuntimeException(errorMsg);
        }
    }


    public static boolean isNumeric(Double doublee) {
        try {
            BigDecimal bigDecimal = new BigDecimal(doublee);
        } catch (Exception e) {
            return false;//异常 说明包含非数字。
        }
        return true;
    }

    /**
     * @param inpatNum 76615-1
     * @param day      yyyy-MM-dd
     */
    private void computeSummary(String inpatNum, String day) {
        //出入量带入的时间 15号的体温单带入  16号7点的出入量总计
        //尿量带入时间为   当天    15号带入  15号护理文书中的24小时尿量总计
        String inOutTotalSummary = patientTemperatureMapper.queryNurseStatistics(inpatNum, DateUtil.dateToString(DateUtil.getDateAfter(DateUtil.stringToDate(day), 1), "yyyy-MM-dd"), "0");
        if (StringUtils.isNotBlank(inOutTotalSummary) && inOutTotalSummary.split("-").length == 12) {
            if ("24".equals(inOutTotalSummary.split("-")[0])) {
                patientTemperatureMapper.saveInAndOut(inpatNum, day, inOutTotalSummary.split("-")[6], inOutTotalSummary.split("-")[11]);
            } else {
                patientTemperatureMapper.saveInAndOut(inpatNum, day, inOutTotalSummary.split("-")[6] + "(" + inOutTotalSummary.split("-")[0] + "h)", inOutTotalSummary.split("-")[11] + "(" + inOutTotalSummary.split("-")[0] + "h)");
            }
        } else {
            patientTemperatureMapper.saveInAndOut(inpatNum, day, "", "");
        }
        //24h尿量
        //2021-1-20修改，尿量隔天，与出入量时间一致
        String urineVolume = patientTemperatureMapper.queryNurseStatistics(inpatNum, DateUtil.dateToString(DateUtil.getDateAfter(DateUtil.stringToDate(day), 1), "yyyy-MM-dd"), "6");
        if (StringUtils.isNotBlank(urineVolume)) {
            String urineStr = urineVolume.substring(urineVolume.indexOf("小时尿量") + 4, urineVolume.indexOf("ml"));
            //当前时间如果有导尿医嘱 尿量后需要加/C
            String isHasC = patientTemperatureMapper.queryisHasC(inpatNum, DateUtil.dateToString(DateUtil.getDateAfter(DateUtil.stringToDate(day), 1), "yyyy-MM-dd"));
            if (StringUtils.isNotBlank(isHasC)) {
                urineStr = urineStr + "/C";
            }
            if ("24".equals(urineVolume.substring(0, 2))) {
                patientTemperatureMapper.saveUrineVolume(inpatNum, day, urineStr);
            } else {
                patientTemperatureMapper.saveUrineVolume(inpatNum, day, urineStr + "(" + urineVolume.substring(0, urineVolume.indexOf("小时尿量")) + "h)");
            }
        } else {
            patientTemperatureMapper.saveUrineVolume(inpatNum, day, "");
        }
    }


}
